<?php
namespace Admin\Controller;

class FeedbackController extends AdminController {

	public function _initialize(){
		parent::_initialize();
		$this->feedback = D('Feedback');
	}

	public function index(){
		if (IS_POST) {
			$data['title'] = I('title','','trim');
			$data['feed_type'] = I('feed_type','','trim');
			S('feedback_config',$data);
			$this->success('更新成功！');
		}else{
			$data = S('feedback_config');
			if (empty($data)) {
				$data = array(
					'title' => '建议反馈',
					'feed_type'  => "1:建议\n2:反馈",
				);
				S('feedback_config',$data);
			}
			$configBuilder = new \Admin\Builder\AdminConfigBuilder();
			$configBuilder->title('留言配置')
			->keyText('title', '留言标题')
			->keyTextArea('feed_type','留言类型')
			->data($data)
			->buttonSubmit()->buttonBack()
			->display();
		}
	}

	public function lists(){
		$map = array();

		$list = $this->feedback->where($map)->page($page, $r)->order('create_time desc')->select();
		foreach ($list as $key => $value) {
			$value['status_text'] = trim($value['reply']) != '' ? '<span class="am-text-primary">已回复</span>' : '<span class="am-text-danger">未回复</span>';
			$list[$key] = $value;
		}
		$totalCount = $this->feedback->where($map)->count();

		$listBuilder = new \Admin\Builder\AdminListBuilder();

		$listBuilder->title('留言列表')
			->keyId()
			->keyText('title', '留言标题')->keyCreateTime()->keyUpdateTime()->keyText('status_text', '状态')
			->keyDoActionEdit('edit?id=###')
			->keyDoAction('delete?id=###','删除')
			->data($list)
			->pagination($totalCount, $r)
			->display();
	}

	public function edit(){
		$id = I('id','','trim,intval');
		if ($id) {
			$map['id'] = $id;
		}else{
			$this->error(L("No this Guestbook"));
		}
		if (IS_POST) {
			$data = $this->feedback->create();
			if ($data) {
				$result = $this->feedback->where($map)->save($data);
				if ($result) {
					$this->success('action success');
				}else{
					$this->error(L("action error"));
				}
			}else{
				$this->error($this->feedback->getError());
			}
		}else{
			$data = $this->feedback->where($map)->find();
			$configBuilder = new \Admin\Builder\AdminConfigBuilder();
			$configBuilder->title('回复留言<small>“'.$data['title'].'”</small>')
			->keyHidden('id')->keyReadOnly('title', '留言标题')
			->keyTextArea('content','留言内容')
			->keyTextArea('reply','回复内容')
			->buttonSubmit()->buttonBack()
			->data($data)
			->display();
		}
	}

	public function delete(){
		$id = I('get.id','','trim');
		if ($id) {
			$wherearr['id'] = $id;
			$result = $this->feedback->where($wherearr)->delete();
			if ($result) {
				$this->success(L("DELETE SUCCESS"));
			}else{
				$this->error(L("DELETE ERROR"));
			}
		}else{
			$this->error(L("No this Guestbook"));
		}
	}
}